package main

import (
	"context"
	authpb "coolcar/auth/api/gen/v1"
	rentalpb "coolcar/rental/api/gen/v1"
	"coolcar/shared/server"
	"log"
	"net/http"

	"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
	"google.golang.org/grpc"
	"google.golang.org/protobuf/encoding/protojson"
)

func main() {
	logger, err := server.NewZapLogger()
	if err != nil {
		log.Fatalf("cannot create logger %v\n", err)
	}
	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()
	mux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{MarshalOptions: protojson.MarshalOptions{
		UseEnumNumbers:  true,
		EmitUnpopulated: true,
		UseProtoNames:   true,
	}}))
	options := []grpc.DialOption{grpc.WithInsecure()}
	serverConfig := []struct {
		name         string
		addr         string
		registerFunc func(context.Context, *runtime.ServeMux, string, []grpc.DialOption) error
	}{
		{
			name: "auth",
			addr: "localhost:8081",
			registerFunc: func(ctx context.Context, mux *runtime.ServeMux, addr string, options []grpc.DialOption) error {
				return authpb.RegisterAuthServiceHandlerFromEndpoint(ctx, mux, "localhost:8081", options)
			},
		}, {
			name: "trip",
			addr: "localhost:8082",
			registerFunc: func(ctx context.Context, mux *runtime.ServeMux, addr string, options []grpc.DialOption) error {
				return rentalpb.RegisterTripServiceHandlerFromEndpoint(ctx, mux, addr, options)
			},
		},
	}
	for _, srv := range serverConfig {
		log.Printf("service %v resiger ....", srv.name)
		err := srv.registerFunc(ctx, mux, srv.addr, options)
		if err != nil {

			logger.Sugar().Fatalf("can not start %v  grpc getway : %v", srv.name, err)
		}
	}
	addr := ":8080"
	logger.Sugar().Infof("grpc gateway started listen in %s", addr)
	err = http.ListenAndServe(addr, mux)
	if err != nil {
		logger.Sugar().Fatalf("can not ListenAndServe : %v", err)

	}
}
